<?php

namespace IDock\Insurance\ZSIC\Request;

use Exception;
use IDock\Insurance\ZSIC\Request\AllZSICRequest;
use IDock\Insurance\ZSIC\Response\UnderwritingResponse;
use IDock\Insurance\ZSIC\Response\VehicleModelResponse;
use IDock\Insurance\ZSIC\ZSICEnums;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\Premium\PremiumRelationVisitor;
use IDock\Visitor\Premium\PremiumUnderwritingVisitor;
use IDock\Visitor\SpecialClausesVisitor;
use IDock\Visitor\VehicleModelVisitor;

/**
 * 核保
 */
class UnderwritingRequest extends AllZSICRequest
{
    protected $response = UnderwritingResponse::class;

    protected $urlTip = '核保';

    public $requestCode = 'generateProposal';

    /**
     * @var PremiumInquiryVisitor $visitor
     */
    protected $visitor;

    public function generate(): array
    {
        $arr = [
            'base' => [
                'quotationNo' => $this->visitor->getExtInfoVisitor()->argc['quotationNo'] ?? '',
                'disputeResolution' => '01',//仲裁
                'disputeOrg' => '',
                'vciProposalNo' => $this->visitor->getExtInfoVisitor()->argc['vciProposalNo'] ?? '',//商业险上次投保单
                'tciProposalNo' => $this->visitor->getExtInfoVisitor()->argc['tciProposalNo'] ?? '',//交强险上次投保单号
                'vciProductVersion' => $this->visitor->getVehicleVisitor()->isNewEnergy ? 'NE' : '20',
                'comment' => $this->visitor->getExtInfoVisitor()->underwriteMsg
            ],
            'parties' => $this->getParty(),
        ];
        if (!empty($this->visitor->getUnderwritingVisitor()->specialClausesList)) {
            $arr['clauses'] = $this->getClauses();
        }
        if (!empty($this->visitor->getNonCarUnderwritingVisitor()->getNonCarList())) {
            $arr['nonVehicleProducts'] = $this->getNonCarList();
        }
        return $arr;
    }

    public function getNonCarList()
    {
        $item = [];
        /*** @var NonCarProductVisitor $single */
        $single = $this->visitor->getNonCarUnderwritingVisitor()->getNonCarList()[0] ?? [];
        $item['productCode'] = $single->productCode;
        $item['planCode'] = $single->planCode;
        $item['effectiveDate'] = date('Y-m-d', strtotime($this->visitor->biStartData ?: $this->visitor->ciStartData));
        $item['expiryDate'] = date('Y-m-d', strtotime($this->visitor->biEndData ?: $this->visitor->ciEndData));
        $item['purchaseNumber'] = $single->insuredNum;
        $item['unitPremium'] = $single->premium;
        return ['nonVehicleProduct' => $item];
    }


    public function getParty()
    {
        $apply = $this->setParty($this->visitor->getApplicantVisitor());
        $apply['insuredFlag'] = '2';
        $owner = $this->setParty($this->visitor->getOwnerVisitor());
        $owner['insuredFlag'] = '3';
        $insured = $this->setParty($this->visitor->getInsuredVisitor());
        $insured['insuredFlag'] = '1';
        return ['party' => [$apply, $insured, $owner]];
    }

    public function setParty($model)
    {
        /**@var PremiumRelationVisitor $model */
        $arr = [
            'insuredFlag' => '',
            'customerType' => $model->typeCode == 'R1' ? '1' : '2',
            'name' => $model->name,
            'sex' => $this->getGenderByIdCard($model->certificateNo),
            'birthday' => $this->getBirthday($model->certificateNo),
            'idType' => ZSICEnums::$certificateTypeCode[$model->certificateTypeCode] ?? '',
            'idNumber' => $model->certificateNo,
            'telephone' => '',
            'mobile' => $model->mobile,
            'provinceCode' => $model->provinceCode,
            'provinceName' => $model->provinceName,
            'cityCode' => $model->cityCode,
            'cityName' => $model->cityName,
            'areaCode' => $model->areaCode,
            'areaName' => $model->areaName,
            'address' => $model->address,
            'eMail' => $model->email,
            'postCode' => $model->postcode,
            'taxType' => '',//纳税人类型 01 一般纳税人 02 小规模纳税人
            'billBankName' => '',
            'billBankAccount' => '',
            'billRequire' => '',
            'taxIdentificationNo' => '',
            'permanentId' => $model->certificateEndDate == '2099-12-31' ? '1' : '0',
            'idStartDate' => $model->certificateStartDate,
            'idExpireDate' => $model->certificateEndDate,
            'nationality' => 'CHN',
            'occupation' => '',
            'businessScop' => '',
            'contactPerson' => $model->linkManName,
            'contactPersonIdType' => ZSICEnums::$certificateTypeCode[$model->linkManCertificateTypeCode] ?? '',
            'contactPersonIdNumber' => $model->linkManCertificateNo,
            'relationShip' => $model->typeCode == 'R1' ? '1' : '2',//与车辆关系 1 车辆所有人  2 车辆管理人
            'phoneOwnerName' => $model->name,
            'phoneOwnerIdType' => ZSICEnums::$certificateTypeCode[$model->certificateTypeCode] ?? '',
            'phoneOwnerIdNumber' => $model->certificateNo,
            'payAccountName' => '',
            'payRelationshipCode' => '',
            'payRelationshipComment' => '',
            'organizationType' => '',
            'industry' => '',
            'isIndividualBusiness' => '',
        ];
        if ($arr['customerType'] == '2') {
            $arr['taxType'] = '01';
        }
        return $arr;
    }

    public function getClauses()
    {
        $list = [];
        $specialClausesList = $this->visitor->getUnderwritingVisitor()->specialClausesList;
        /**@var SpecialClausesVisitor $value * */
        foreach ($specialClausesList as $value) {
            $tmp = [
                'clauseCode' => $value->clauseName,
                'clauseName' => $value->clauseName,
                'customizedContent' => $value->clauseContent,
                'productCode' => $value->riskType == 'TCI' ? 'MAUTO' : 'GAUTO',
            ];
            $list[] = $tmp;
            unset($tmp);
        }
        return ['clause' => $list];
    }

    /**
     * 通过身份证获取性别
     * @param $idCard
     * @return int
     * @throws
     */
    private function getGenderByIdCard($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard, 16, 1)) % 2;
        return $gender ? '1' : '2';
    }

    /**
     * 通过身份证获取生日
     * @param $idCard
     * @return string
     * @throws
     */
    private function getBirthday($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new Exception("身份证位数不合法");
        }
        return substr($idCard, 6, 4) . '-' . substr($idCard, 10, 2) . '-' . substr($idCard, 12, 2);
    }

    public function getBusinessNo()
    {
        return $this->visitor->getExtInfoVisitor()->argc['businessNo'] ?? '';
    }
}
